﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChgDoc.Entity;
using System.Web;
using StackExchange.Profiling;
using System.Text.RegularExpressions;

namespace ChgDoc.Render
{
    public class Toolbox
    {
        private readonly Template _template;
       
        public Toolbox(Template template)
        {
            _template = template;
        }

        public int ArticleId { get; set; }
	
        public string EditLink
        {
            get { return Config.BaseUrl + "edit/templateedit.aspx?id=" + _template.Id + "&returnurl=" + HttpContext.Current.Request.RawUrl; }
        }

        public List<dynamic> Exec(string code, params string[] parameters)
        {
            SqlStatement query = SqlStatement.ForCode(code);
            if (query == null)
                return null;

            return query.GetResults(parameters);
        }

        public string ArticleAttribute( long entityId, string code, string defaultValue = "" )
        {
            var attribute = EntityAttribute.Find( EntityType.Article, entityId, code );
            if (attribute == null)
                return defaultValue;

            return attribute.Value;
        }

        public string FirstParagraph( string input )
        {
            int close = input.IndexOf( "</p>", StringComparison.OrdinalIgnoreCase );
            if (close == -1)
                return StripHtml( input );

            int open = input.IndexOf( "<p", StringComparison.OrdinalIgnoreCase );
            if (open != -1)
                open = input.IndexOf( ">", open );

            if (open == -1 || open > close)
                return StripHtml( input );

            return StripHtml( input.Substring( open + 1, close - open - 1 ) );            
        }

        static Regex _htmlRegex = new Regex( "<.*?>", RegexOptions.Compiled );

        public string StripHtml( string input )
        {
            return _htmlRegex.Replace( input, string.Empty );
        }        
    }
}
